/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Persistencia;

import Excepciones.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;

/**
 *
 * @author diego
 */
public class JpaController implements Serializable {

    public JpaController() {
    }

    public void create(Object objeto) {
        EntityManager em = null;
        em = ConexionAdmin.getInstance().getEntityManager();
        em.persist(objeto);

    }

    public void commit() {
        ConexionAdmin.getInstance().commit();
    }

    public void rollback() {
        ConexionAdmin.getInstance().rollback();
    }

    public void begin() {
        ConexionAdmin.getInstance().begin();
    }

    public void edit(Object objeto) {
        EntityManager em = null;
        try {
            em = ConexionAdmin.getInstance().getEntityManager();
            objeto = em.merge(objeto);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void destroy(Class clase, Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        em = ConexionAdmin.getInstance().getEntityManager();
        Object objeto;
        try {
            objeto = em.getReference(clase, id);
        } catch (EntityNotFoundException enfe) {
            enfe.printStackTrace();
            throw new NonexistentEntityException("No existe objeto con id:" + id, enfe);
        }
        em.remove(objeto);
    }

    public List findEntities(Class clase) {
        EntityManager em = ConexionAdmin.getInstance().getEntityManager();
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(clase));
        Query q = em.createQuery(cq);

        return q.getResultList();
    }

    public Object find(Class clase, Long id) {
        EntityManager em = ConexionAdmin.getInstance().getEntityManager();
        return em.find(clase, id);

    }
}
